package com.ccx.demo.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMq 配置
 *
 * @author 谢长春 2022-03-15
 */
@Slf4j
@Configuration
@ConditionalOnProperty(value = "spring.app.rabbitmq.enabled", havingValue = "true")
@ConfigurationProperties(prefix = "spring.app.rabbitmq")
public class RabbitMqConfiguration {
    @Setter
    @Getter
    private String topicExchangeName;
    @Setter
    @Getter
    private String defaultQueueName;
    @Setter
    @Getter
    private String defaultQueueRoutingKey;
    @Setter
    @Getter
    private int defaultQueuePriority;
    @Setter
    @Getter
    private String testQueueName;
    @Setter
    @Getter
    private String testQueueRoutingKey;
    @Setter
    @Getter
    private int testQueuePriority;

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(topicExchangeName);
    }

    @Bean
    Queue defaultQueue() {
        final Map<String, Object> args = new HashMap<>();
        args.put("x-max-priority", defaultQueuePriority);
        return new Queue(defaultQueueName, false, false, false, args);
    }

    @Bean
    Binding defaultQueueBinding(final Queue defaultQueue, final TopicExchange exchange) {
        log.info("topicExchangeName:{}, defaultQueueName:{}, defaultQueueRoutingKey:{}, defaultQueuePriority:{}, "
                , topicExchangeName
                , defaultQueueName
                , defaultQueueRoutingKey
                , defaultQueuePriority
        );
        // defaultQueueRoutingKey + ".#"
        // # 表示零个或多个词
        // * 表示一个词
        return BindingBuilder.bind(defaultQueue).to(exchange).with(defaultQueueRoutingKey);
    }

    @Bean
    Queue testQueue() {
        final Map<String, Object> args = new HashMap<>();
        args.put("x-max-priority", testQueuePriority);
        return new Queue(testQueueName, false, false, false, args);
    }

    @Bean
    Binding testQueueBinding(final Queue testQueue, final TopicExchange exchange) {
        log.info("topicExchangeName:{}, testQueueName:{}, testQueueRoutingKey:{}, testQueuePriority:{}, "
                , topicExchangeName
                , testQueueName
                , testQueueRoutingKey
                , testQueuePriority
        );
        // defaultQueueRoutingKey + ".#"
        // # 表示零个或多个词
        // * 表示一个词
        return BindingBuilder.bind(testQueue).to(exchange).with(testQueueRoutingKey);
    }

}
